
import { useFetch } from "@vueuse/core";

interface RequestOptions {
  method?: string;
  headers?: Record<string, string>;
  body?: any;
}

interface ApiResponse<T> {
  data: T | null;
  error: Error | null;
  isFetching: boolean;
  execute: (body?: any) => Promise<void>;
}

export const useApi = <T>(
  endpoint: string,
  method: string = "GET",
  headers: Record<string, string> = {},
  body: any = null
): ApiResponse<T> => {
  const baseUrl = "https://api.example.com"; // 替换为你的基础 URL
  const url = `${baseUrl}${endpoint}`;

  // 请求拦截器 - 在这里可以统一处理请求头、添加认证信息等
  const requestInterceptor = (options: RequestOptions): RequestOptions => {
    const token = localStorage.getItem("auth_token");
    if (token) {
      options.headers = {
        ...options.headers,
        Authorization: `Bearer ${token}`,
      };
    }
    return options;
  };

  const defaultOptions: RequestOptions = {
    method,
    headers: {
      "Content-Type": "application/json",
      ...headers,
    },
    body: body ? JSON.stringify(body) : null,
  };

  // 使用 useFetch 发起请求
  const { data, error, isFetching, execute } = useFetch(
    url,
    requestInterceptor(defaultOptions)
  ).json<T>(); // 期望返回泛型数据类型 T

  // 解构 .value，直接获取数据
  const rawData = data.value;
  const rawError = error.value;
  const rawIsFetching = isFetching.value;
  // 响应拦截器 - 处理响应前的状态检查
  const responseInterceptor = (response: Response) => {
    if (response.status >= 400) {
      console.error(`请求失败，状态码: ${response.status}`);
      return Promise.reject(new Error(`请求失败，状态码: ${response.status}`));
    }
    return response.json(); // 返回解析后的 JSON 数据
  };

  // 在执行请求时，处理响应
  const handleResponse = async () => {
    try {
      const response = await execute(); // 执行请求
      await responseInterceptor(response); // 调用响应拦截器处理响应
    } catch (err) {
      console.error("处理请求失败:", err);
    }
  };

  // 错误处理
  if (error.value) {
    console.error("API 请求失败:", error.value);
  }

  return {
    data: rawData,
    error: rawError,
    isFetching: rawIsFetching,
    execute: handleResponse, // 用新的 handleResponse 来处理请求
  };
};
